package com.hzy.yiyaoba.adapter;

import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.hzy.yiyaoba.R;
import com.hzy.yiyaoba.R.id;
import com.hzy.yiyaoba.bean.Lore;
import com.hzy.yiyaoba.ui.LoreDetailActivity;
import com.hzy.yiyaoba.utils.BitmapManager;
import com.hzy.yiyaoba.utils.Config.LoreConfig;
import com.lidroid.xutils.BitmapUtils;

public class LoreListAdapter extends BaseAdapter implements OnClickListener {

	Context mContext;
	LayoutInflater mInflater;
	List<Lore> mLores;
	BitmapUtils mBmpUtils;

	public LoreListAdapter(Context context, List<Lore> lores) {
		mLores = lores;
		mContext = context;
		mInflater = LayoutInflater.from(context);
		mBmpUtils = BitmapManager.getInstance(mContext).getBitmapUtils();
	}

	@Override
	public int getCount() {
		return mLores.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	class ViewHolder {
		ImageView mIcon;
		TextView mTitle;
		TextView mClass;
		TextView mTime;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.common_main_list_item, null);
			holder = new ViewHolder();
			convertView.setTag(holder);
			convertView.setOnClickListener(this);
			holder.mIcon = (ImageView) convertView.findViewById(id.common_main_list_icon);
			holder.mTitle = (TextView) convertView.findViewById(id.common_main_list_title);
			holder.mClass = (TextView) convertView.findViewById(id.common_main_list_class);
			holder.mTime = (TextView) convertView.findViewById(id.common_main_list_time);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		Lore item = mLores.get(position);
		convertView.setTag(id.tag_second, item);
		mBmpUtils.display(holder.mIcon, item.getImg());
		holder.mTitle.setText(item.getTitle());
		holder.mClass.setText(mContext.getString(R.string.common_publish_class) + item.getClassName());
		holder.mTime.setText(mContext.getString(R.string.common_publish_time) + new Date(item.getTime()).toLocaleString());
		return convertView;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case id.common_main_list_area:
			performItemClick(v);
			break;

		default:
			break;
		}
	}

	private void performItemClick(View v) {
		Lore item = (Lore) v.getTag(id.tag_second);
		int loreId = item.getId();
		String imageUrl = item.getImg();
		Intent i = new Intent(mContext, LoreDetailActivity.class);
		i.putExtra(LoreConfig.EXTRA_LORE_ID, loreId);
		i.putExtra(LoreConfig.EXTRA_IMAGE_URL, imageUrl);
		mContext.startActivity(i);
	}

}
